package com.demo.utils;

import com.demo.config.DatabaseConfig;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class DatabaseUtils {
    private static final Logger log = LogManager.getLogger(DatabaseUtils.class);

    /**
     * 执行查询并返回结果
     */
    public static void executeQuery(String sql, Object... params) {
        try (Connection conn = DatabaseConfig.getDataSource().getConnection();
             PreparedStatement stmt = conn.prepareStatement(sql)) {

            // 设置参数
            for (int i = 0; i < params.length; i++) {
                stmt.setObject(i + 1, params[i]);
            }

            try (ResultSet rs = stmt.executeQuery()) {
                // 处理查询结果（示例：打印结果）
                int columnCount = rs.getMetaData().getColumnCount();
                while (rs.next()) {
                    StringBuilder row = new StringBuilder();
                    for (int i = 1; i <= columnCount; i++) {
                        row.append(rs.getObject(i)).append("\t");
                    }
                    log.info(row.toString());
                }
            }
        } catch (SQLException e) {
            log.error("数据库查询失败", e);
            throw new RuntimeException("数据库查询失败", e);
        }
    }

    /**
     * 执行更新（INSERT/UPDATE/DELETE）
     */
    public static int executeUpdate(String sql, Object... params) {
        try (Connection conn = DatabaseConfig.getDataSource().getConnection();
             PreparedStatement stmt = conn.prepareStatement(sql)) {

            // 设置参数
            for (int i = 0; i < params.length; i++) {
                stmt.setObject(i + 1, params[i]);
            }

            return stmt.executeUpdate();
        } catch (SQLException e) {
            log.error("数据库更新失败", e);
            throw new RuntimeException("数据库更新失败", e);
        }
    }
}